// 请求拦截器配置
$(document).ready(function() {
    // 设置全局的AJAX请求拦截器
    $.ajaxSetup({
        beforeSend: function(xhr) {
            const token = localStorage.getItem('token');
            if (token) {
                xhr.setRequestHeader('Authorization', 'Bearer ' + token);
            }
        },
        complete: function(xhr) {
            // 处理401未授权响应
            if (xhr.status === 401) {
                console.log('Token已过期或无效，正在跳转到登录页面...');
                localStorage.removeItem('token');
                // 判断当前是否在管理员页面
                if (window.location.pathname.startsWith('/admin')) {
                    window.location.href = '/admin/login';
                } else {
                    window.location.href = '/login';
                }
            }
        },
        error: function(xhr) {
            // 处理403禁止访问响应
            if (xhr.status === 403) {
                console.log('没有访问权限');
                alert('您没有权限访问此资源');
            }
        }
    });
});

// 检查登录状态
function checkLoginStatus() {
    const token = localStorage.getItem('token');
    if (!token) {
        console.log('未找到token，跳转到登录页面');
        if (window.location.pathname.startsWith('/admin')) {
            window.location.href = '/admin/login';
        } else {
            window.location.href = '/login';
        }
        return false;
    }
    return true;
}

// 退出登录
function logout() {
    localStorage.removeItem('token');
    if (window.location.pathname.startsWith('/admin')) {
        window.location.href = '/admin/login';
    } else {
        window.location.href = '/login';
    }
} 